package com.xcw.bos.service.impl;

import java.sql.Timestamp;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.xcw.bos.crm.CustomerService;
import com.xcw.bos.dao.IDecidedZoneDao;
import com.xcw.bos.dao.INoticebillDao;
import com.xcw.bos.dao.IWorkbillDao;
import com.xcw.bos.domain.DecidedZone;
import com.xcw.bos.domain.Noticebill;
import com.xcw.bos.domain.Staff;
import com.xcw.bos.domain.User;
import com.xcw.bos.domain.Workbill;
import com.xcw.bos.page.PageBean;
import com.xcw.bos.service.INoticebillService;
/**
 * 业务通知单操作Service
 * @author xcw
 *
 */
@Service
@Transactional
public class NoticebillServiceImpl implements INoticebillService {
    @Resource
    private INoticebillDao noticebillDao;
    @Resource
    private IDecidedZoneDao decidedZoneDao;
    @Resource
    private IWorkbillDao workbillDao;
    @Resource
    private CustomerService customerService;
    
    public void pageQuery(PageBean<Noticebill> pageBean){
    	noticebillDao.pageQuery(pageBean);
    }
    
    //保存业务通知单，并自动分单
    public void save(Noticebill model, String userid){
    	User user = new User();
    	user.setId(userid);//托管对象
    	model.setUser(user);//关联托管对象
    	noticebillDao.save(model);//持久状态对象
    	
    	//取件地址
    	String pickaddress = model.getPickaddress();
    	String decidedZoneId = customerService.findDecidedZoneIdByPickAddress(pickaddress);
    	//自动分单---将客户的取货任务分配取派员，产生工单
    	if(decidedZoneId != null){
    		//查询到定区id,可以自动分单
    		DecidedZone decidedZone = decidedZoneDao.findById(decidedZoneId);
    		Staff staff = decidedZone.getStaff();//取派员
    		model.setStaff(staff);//关联取派员
    		model.setOrdertype("自动");//设置分单类型为：自动
    		
    		//产生工单
    		Workbill workbill = new Workbill();
    		workbill.setAttachbilltimes(0);
    		workbill.setBuildtime(new Timestamp(System.currentTimeMillis()));
    		workbill.setNoticebill(model);
    		workbill.setPickstate("新单");
    		workbill.setRemark(model.getRemark());
    		workbill.setStaff(staff);
    		workbill.setType("新");
    		
    		//保存工单
    		workbillDao.save(workbill);
    		
    	}else{
    		//没有查询到定区id，需要人工分单
    		model.setOrdertype("手动");//设置分单类型为：自动
    	}
    }
}
